<template>
	<view class="orders-container">
		<!-- 头部导航栏 -->
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-content">
					<view class="header-left" @click="closePage">
						<text class="cuIcon-back"></text>
					</view>
					<view class="header-center">
						<text class="header-title">订单管理</text>
					</view>
				</view>
			</template>
		</headerSlot>

		<!-- 主要内容 -->
		<view class="main-content">

			<!-- 筛选栏 -->
			<view class="filter-tabs">
				<view class="tab-list">
					<view class="tab-item" :class="{ active: currentStatus === '' }" @click="filterByStatus('')">
						<text>全部</text>
					</view>
					<view class="tab-item" :class="{ active: currentStatus === 'pending' }"
						@click="filterByStatus('pending')">
						<text>待付款</text>
					</view>
					<view class="tab-item" :class="{ active: currentStatus === 'paid' }"
						@click="filterByStatus('paid')">
						<text>已付款</text>
					</view>
					<view class="tab-item" :class="{ active: currentStatus === 'shipped' }"
						@click="filterByStatus('shipped')">
						<text>已发货</text>
					</view>
					<view class="tab-item" :class="{ active: currentStatus === 'completed' }"
						@click="filterByStatus('completed')">
						<text>已完成</text>
					</view>
				</view>
			</view>

			<!-- 订单列表 -->
			<view class="order-list">
				<view class="order-item" v-for="order in orderList" :key="order._id"
					@click="goToOrderDetail(order._id)">
					<view class="order-header">
						<text class="order-id">订单号：{{ order.orderNo }}</text>
						<text class="order-status" :class="'status-' + order.status">
							{{ getStatusText(order.status) }}
						</text>
					</view>

					<view class="order-content">
						<view class="product-list">
							<view class="product-item" v-for="item in order.products" :key="item._id">
								<image class="product-image" :src="getProductImage(item)" mode="aspectFill"></image>
								<view class="product-info">
									<text class="product-name">{{ getProductName(item) }}</text>
									<text class="product-spec">{{ getProductSpec(item) }}</text>
									<view class="product-price-qty">
										<text class="product-price">¥{{ formatMoney(item.price) }}</text>
										<text class="product-qty">x{{ item.quantity }}</text>
									</view>
								</view>
							</view>
						</view>

						<view class="order-summary">
							<text class="total-amount">共{{ getTotalQuantity(order.products) }}件商品</text>
							<text class="total-price">合计：¥{{ formatMoney(order.totalAmount) }}</text>
						</view>
					</view>

					<view class="order-footer">
						<text class="order-time">{{ formatDate(order.createTime) }}</text>
						<view class="order-actions">
							<text class="action-btn" v-if="order.status === 'paid'"
								@click.stop="confirmShip(order._id)">确认发货</text>
							<text class="action-btn" v-if="order.status === 'shipped' && !isMerchant"
								@click.stop="confirmComplete(order._id)">确认完成</text>
							<text class="action-btn danger" v-if="order.status === 'pending' || order.status === 'paid'"
								@click.stop="cancelOrder(order._id)">取消订单</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="hasMore" class="loading" @click="loadMore">
				<text v-if="loading">加载中...</text>
			</view>

			<!-- 无数据提示 -->
			<view v-if="orderList.length === 0 && !loading" class="empty-state">
				<text class="empty-desc">暂无订单,请耐心等待买家下单</text>
			</view>
		</view>

		<!-- 日期选择器 -->
		<uni-popup ref="datePicker" type="bottom" @change="onDatePickerChange">
			<view class="date-picker-content">
				<view class="picker-header">
					<text @click="cancelDatePicker">取消</text>
					<text class="picker-title">选择日期范围</text>
					<text @click="confirmDatePicker">确定</text>
				</view>
				<picker mode="date" :value="startDate" @change="onStartDateChange">
					<view class="date-input">
						<text>开始日期：{{ startDate }}</text>
					</view>
				</picker>
				<picker mode="date" :value="endDate" @change="onEndDateChange">
					<view class="date-input">
						<text>结束日期：{{ endDate }}</text>
					</view>
				</picker>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getShopOrders,
		confirmShip,
		confirmComplete,
		cancelShopOrder
	} from '@/api/shop.js'
	import headerSlot from '@/components/header-slot.vue'

	export default {
		components: {
			headerSlot
		},
		data() {
			return {
				orderList: [],
				currentStatus: '',
				searchKeyword: '',
				showSearch: false,
				showDatePicker: false,
				startDate: '',
				endDate: '',
				page: 1,
				limit: 10,
				hasMore: true,
				loading: false
			}
		},
		computed: {
			dateRangeText() {
				if (!this.startDate && !this.endDate) {
					return '选择日期'
				}
				if (this.startDate && this.endDate) {
					return `${this.startDate} 至 ${this.endDate}`
				}
				return this.startDate || this.endDate
			},
			// 判断是否为商户
			isMerchant() {
				const userInfo = this.$store.state.userInfo || {};
				return userInfo.shops && userInfo.shops.length > 0;
			}
		},
		onLoad() {
			this.initDateRange()
			this.loadOrders()
		},
		methods: {
			// 关闭页面
			closePage() {
				uni.navigateBack()
			},

			// 初始化日期范围（默认最近7天）
			initDateRange() {
				const end = new Date()
				const start = new Date()
				start.setDate(start.getDate() - 7)

				this.endDate = this.formatDateForPicker(end)
				this.startDate = this.formatDateForPicker(start)
			},

			// 格式化日期为picker格式
			formatDateForPicker(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},

			// 加载订单列表
			async loadOrders(refresh = false) {
				try {
					this.loading = true
					if (refresh) {
						this.page = 1
						this.orderList = []
					}

					const params = {
						page: this.page,
						limit: this.limit,
						status: this.currentStatus
					}

					// 添加搜索关键词
					if (this.searchKeyword.trim()) {
						params.keyword = this.searchKeyword.trim()
					}


					const res = await getShopOrders(params)
					if (res.data.code === 200) {
						const newOrders = res.data.data.list || []
						if (refresh) {
							this.orderList = newOrders
						} else {
							this.orderList = [...this.orderList, ...newOrders]
						}

						// 判断是否还有更多数据
						const total = res.data.data.pagination.total
						const currentTotal = this.orderList.length
						this.hasMore = currentTotal < total

						if (newOrders.length === 0 && this.page > 1) {
							this.page--
						}
					}
				} catch (error) {
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},

			// 按状态筛选
			filterByStatus(status) {
				this.currentStatus = status
				this.loadOrders(true)
			},

			// 搜索订单
			searchOrders() {
				this.loadOrders(true)
			},

			// 加载更多
			loadMore() {
				if (!this.hasMore || this.loading) return
				this.loadOrders(false)
			},

			// 格式化金额
			formatMoney(amount) {
				return Number(amount || 0).toFixed(2)
			},

			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return ''
				const date = new Date(dateStr)
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hour = String(date.getHours()).padStart(2, '0')
				const minute = String(date.getMinutes()).padStart(2, '0')
				return `${month}-${day} ${hour}:${minute}`
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'pending': '待付款',
					'paid': '已付款',
					'shipped': '已发货',
					'delivered': '已送达',
					'completed': '已完成',
					'cancelled': '已取消'
				}
				return statusMap[status] || '未知状态'
			},

			// 获取商品图片
			getProductImage(item) {
				return item.images && item.images[0] ? item.images[0] : '/static/logo-orange.png'
			},

			// 获取商品名称
			getProductName(item) {
				return item.name || '未知商品'
			},

			// 获取商品规格
			getProductSpec(item) {
				return item.specification || '默认规格'
			},

			// 获取总数量
			getTotalQuantity(products) {
				return products ? products.reduce((total, item) => total + (item.quantity || 0), 0) : 0
			},

			// 跳转到订单详情
			goToOrderDetail(orderId) {
				this.$router.smartNavigate({
					url: `/pages/mePages/shopCenter/orderDetail?id=${orderId}`
				})
			},

			// 确认发货
			async confirmShip(orderId) {
				try {
					const res = await confirmShip(orderId)
					if (res.code === 200) {
						uni.showToast({
							title: '发货成功',
							icon: 'success'
						})
						this.loadOrders(true)
					}
				} catch (error) {
					console.error('确认发货失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},

			// 确认完成
			async confirmComplete(orderId) {
				// 检查是否为商户，商户不允许直接完成订单
				const userInfo = this.$store.state.userInfo || {};
				if (userInfo.shops && userInfo.shops.length > 0) {
					uni.showModal({
						title: '操作限制',
						content: '商户不允许直接完成订单，请联系买家确认收货后自动完成',
						showCancel: false,
						confirmText: '我知道了'
					});
					return;
				}

				try {
					const res = await confirmComplete(orderId)
					if (res.code === 200) {
						uni.showToast({
							title: '操作成功',
							icon: 'success'
						})
						this.loadOrders(true)
					}
				} catch (error) {
					console.error('确认完成失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},

			// 取消订单
			async cancelOrder(orderId) {
				try {
					const res = await cancelShopOrder(orderId)
					if (res.code === 200) {
						uni.showToast({
							title: '订单已取消',
							icon: 'success'
						})
						this.loadOrders(true)
					}
				} catch (error) {
					console.error('取消订单失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			},

			// 联系买家
			contactBuyer(userId) {
				// 这里可以实现联系买家的功能，比如跳转到聊天页面
				uni.showModal({
					title: '联系买家',
					content: '确定要联系买家吗？',
					success: (res) => {
						if (res.confirm) {
							// 可以跳转到聊天页面或拨打电话
							uni.showToast({
								title: '正在跳转到聊天页面...',
								icon: 'none'
							})
							// 这里可以添加跳转到聊天页面的逻辑
							// uni.navigateTo({
							//     url: `/pages/messagePages/chat?userId=${userId}`
							// })
						}
					}
				})
			},

			// 日期选择器相关方法
			onDatePickerChange(e) {
				this.showDatePicker = e.show
			},

			onStartDateChange(e) {
				this.startDate = e.detail.value
			},

			onEndDateChange(e) {
				this.endDate = e.detail.value
			},

			cancelDatePicker() {
				this.$refs.datePicker.close()
			},

			confirmDatePicker() {
				this.$refs.datePicker.close()
				this.loadOrders(true)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.orders-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		padding-bottom: 120rpx;
	}

	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 32rpx;
		background: transparent;
	}

	.header-left,
	.header-right {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.header-center {
		flex: 1;
		text-align: center;
	}

	.header-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.main-content {
		padding: 32rpx;
	}

	.search-bar {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
		backdrop-filter: blur(10rpx);

		.search-input {
			background: #f8f9fa;
			border-radius: 20rpx;
			padding: 24rpx 32rpx;
			font-size: 28rpx;
			border: 1rpx solid #e9ecef;
		}
	}

	.filter-tabs {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 24rpx;
		padding: 10rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
		backdrop-filter: blur(10rpx);

		.tab-list {
			display: flex;
			justify-content: space-between;

			.tab-item {
				flex: 1;
				text-align: center;
				padding: 20rpx 16rpx;
				margin: 0 8rpx;
				border-radius: 16rpx;
				font-size: 28rpx;
				font-weight: bold;
				transition: all 0.3s ease;
				position: relative;

				&:first-child {
					margin-left: 0;
				}

				&:last-child {
					margin-right: 0;
				}

				&.active {
					background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
					color: #fff;
					box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
				}

				&:not(.active) {
					background: #f8f9fa;
					color: #666;
					border: 1rpx solid #e9ecef;
				}
			}
		}
	}

	.order-list {
		.order-item {
			background: rgba(255, 255, 255, 0.95);
			border-radius: 24rpx;
			padding: 40rpx;
			margin-bottom: 32rpx;
			box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
			backdrop-filter: blur(10rpx);
			transition: all 0.3s ease;

			&:active {
				transform: scale(0.98);
			}

			.order-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;

				.order-id {
					font-size: 32rpx;
					color: #333;
					font-weight: bold;
				}

				.order-status {
					font-size: 28rpx;
					padding: 12rpx 20rpx;
					border-radius: 20rpx;
					font-weight: bold;

					&.status-pending {
						background: #fff3e0;
						color: #ff9800;
					}

					&.status-paid {
						background: #e8f5e8;
						color: #4caf50;
					}

					&.status-shipped {
						background: #e3f2fd;
						color: #2196f3;
					}

					&.status-delivered {
						background: #e0f2f7;
						color: #00bcd4;
					}

					&.status-completed {
						background: #e8f5e8;
						color: #4caf50;
					}

					&.status-cancelled {
						background: #ffebee;
						color: #f44336;
					}
				}
			}

			.order-content {
				margin-bottom: 24rpx;

				.product-summary {
					font-size: 30rpx;
					color: #666;
					line-height: 1.5;
					margin-bottom: 16rpx;
				}

				.order-time {
					font-size: 28rpx;
					color: #999;
				}
			}

			.order-footer {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.order-amount {
					font-size: 40rpx;
					font-weight: bold;
					color: #f44336;
				}

				.order-actions {
					display: flex;

					.action-btn {
						font-size: 28rpx;
						color: #fff;
						padding: 16rpx 32rpx;
						background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
						border-radius: 24rpx;
						margin-left: 16rpx;
						box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.3);
						transition: all 0.3s ease;

						&:active {
							transform: scale(0.95);
						}
					}
				}
			}
		}
	}

	.empty-state {
		text-align: center;
		padding: 120rpx 32rpx;

		.empty-icon {
			font-size: 120rpx;
			color: rgba(255, 255, 255, 0.6);
			margin-bottom: 32rpx;
		}

		.empty-text {
			font-size: 32rpx;
			color: rgba(255, 255, 255, 0.8);
			margin-bottom: 16rpx;
		}

		.empty-desc {
			font-size: 28rpx;
			color: rgba(255, 255, 255, 0.6);
		}
	}

	.loading {
		text-align: center;
		padding: 80rpx 32rpx;

		.loading-text {
			font-size: 28rpx;
			color: rgba(255, 255, 255, 0.8);
		}
	}
</style>